package com.M.lock;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author kanlei
 * @email freefree.me@qq.com
 * @since 2021/9/3
 */
@Slf4j
public class MLock extends AbstractLock {

    private ZooKeeper zkCli;
    private List<String> nodes;
    private String flag;
    private String lockName;

    {
        try {
            CountDownLatch latch = new CountDownLatch(1);
            zkCli = new ZooKeeper("localhost:2181", 3000, event -> {
                if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                    log.info("connect successfully");
                    latch.countDown();
                }
            });
            latch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public MLock(String lockName) {
        this.lockName = lockName;
    }

    @Override
    protected boolean tryLock() throws Exception {
        Stat stat = zkCli.exists("/" + lockName, false);
        if (stat == null) {
            try {
                zkCli.create("/" + lockName, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            } catch (Exception e) {
                log.info("{} already created.",lockName);
            }
        }
        if (flag == null) {
            flag = zkCli.create("/" + lockName + "/", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            flag = flag.substring(flag.lastIndexOf("/") + 1);
        }
        getChildren(lockName);
        return flag.equalsIgnoreCase(nodes.get(0));
    }

    @Override
    protected void waitLock() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        zkCli.exists("/" + lockName + "/" + nodes.get(nodes.indexOf(flag) - 1),
                event -> {
                    if (event.getType() == Watcher.Event.EventType.NodeDeleted) {
                        latch.countDown();
                    }
                });
        latch.await();
    }

    @Override
    public void unlock() {
        try {
            zkCli.delete("/" + lockName + "/" + flag, -1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getChildren(String name) throws Exception {
        nodes = zkCli.getChildren("/" + name, false);
        Collections.sort(nodes);
    }
}
